package com.yuzhantao.collection.sensorflow;

import java.util.List;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.yuzhantao.collection.sensorflow.model.UInfo;
import com.yuzhantao.collection.sensorflow.model.UInfoRepository;
import com.yuzhantao.collection.sensorflow.response.message.RackInfoVo;
import com.yuzhantao.collection.sensorflow.response.message.RfidInfo;
import com.yuzhantao.collection.sensorflow.response.message.UInitInfoEntity;

@Service
@Order(2)
public class SensorFlowApplicationRunner implements ApplicationRunner {
	protected static final Logger logger = Logger.getLogger(SensorFlowApplicationRunner.class);
	private RestTemplate restTemplate;
	private ClientHttpRequestFactory factory;

	@Autowired
	UInfoRepository uInfoRepository;

	@Override
	public void run(ApplicationArguments args) {
		try {
//			this.initUInfo(restTemplate);
		} catch (Exception e) {
			logger.error(e);
		}
	}

	private void initUInfo(RestTemplate restTemplate) {
//		String url = "http://192.168.2.117:8080/asset/sensorflow/getAssetRfidAndUInfo";
		String url = "http://211.83.241.142:8080/asset/sensorflow/getAssetRfidAndUInfo";
		UInitInfoEntity uInitInfo = restTemplate.getForObject(url, UInitInfoEntity.class);
		if (uInitInfo == null || uInitInfo.getData() == null)
			return;
		List<RackInfoVo> rackInfos = (List<RackInfoVo>) uInitInfo.getData();
		long unpdateCount = 0;
		for (int i = 0; i < rackInfos.size(); i++) {
			RackInfoVo rack = rackInfos.get(i);
			if (rack == null || rack.getRfidInfoList() == null || rack.getRfidInfoList().size() == 0)
				continue;
			for (RfidInfo rfid : rack.getRfidInfoList()) {
				int uPosition = rfid.getU();
				String deviceCode = rack.getRackConverCode();
				String tag = rfid.getRfid();
				UInfo uInfo = uInfoRepository.findOneByDeviceCodeAndPosition(deviceCode, uPosition);
				if (uInfo == null) {
					uInfo = new UInfo();
				}
				uInfo.setDeviceCode(deviceCode);
				uInfo.setPosition(uPosition);
				uInfo.setTag(tag);
				uInfoRepository.saveAndFlush(uInfo);
				logger.info("[更新数量:" + (++unpdateCount) + "]初始化操作，从远程web获取数据保存到本地数据库中:" + JSON.toJSONString(uInfo));
			}
		}
	}

	@Autowired
	public void setFactory() {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setReadTimeout(5000);
		factory.setConnectTimeout(15000);
		this.factory = factory;
	}

	@Autowired
	public void setRestTemplate() {
		this.restTemplate = new RestTemplate(this.factory);
	}
}
